# coding=utf-8
from flask import  Flask, render_template,request,escape
import requests
import json
import http.client, urllib.request, urllib.parse, urllib.error, base64
from pymysql import connect
from panduan import panduan_login
from gaode import weather
from land import geocode
from poemmaker import poemmake

app = Flask(__name__)
def log_request(req:"flask request",res:str):
	with open("vsearch.log","a") as log:
		print(req.form,req.host_url,req.remote_addr,res,file=log,sep="|")


@app.route('/index',methods=['get','post'])
def hello_entry():
	user = request.form.get("user")
	password = request.form.get("password")
	results=str(user)+str(password)
	log_request(request,results)
	return render_template('index.html')


@app.route('/login',methods=['get'])
def login():
	return render_template('login.html')


@app.route('/logining',methods=['POST'])
def logining() -> 'html':
	user = request.form.get("user") 
	password = request.form.get("password")
	results=str(user)+str(password)
	log_request(request,results)
	denglu = panduan_login(user, password)
	if denglu == "true":
		return render_template('index.html')
	else:
		return render_template('login_fail.html')


@app.route('/add_admin',methods=["GET","post"])
def addstudent_page() -> "html":
	return render_template("add_admin.html")


@app.route('/add_process',methods=["POST"])
def add_student():
	con = connect(host="127.0.0.1",port=3306,user="root",password="zdn0203..",db="sten")
	cursor2 = con.cursor()
	username = request.form.get("username")
	mima = request.form.get("mima")
	sql = "insert into admin set username='%s',password='%s'"%(username,mima)
	cursor2.execute(sql)
	con.commit()
	return render_template("success_add.html")

@app.route("/viewlog")
def view_log():
	contents=[]
	with open("vsearch.log","r") as log:
		for line in log:
			contents.append([])
			for item in line.split("|"):
				contents[-1].append(escape(item))
		titles= ["Formdata","Host_url","Remote_addr"]
	return render_template('view.html',the_data=contents,the_titles=titles)


@app.route('/plant',methods=['get','post'])
def plant()->'html':
	return render_template('plant.html')

@app.route('/plant_page',methods=['post'])
	# 本地植物识别
def plant_page():
	path=request.form['path']
	f = open(path, 'rb')
	img = base64.b64encode(f.read())
	params = {"image":img,'baike_num':4}
	request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant"
	access_token='24.18c156264044eed43c0f5686eb490329.2592000.1613120716.282335-23488180'
	request_url = request_url + "?access_token=" + access_token
	headers = {'content-type': 'application/x-www-form-urlencoded'}
	response = requests.post(request_url, data=params, headers=headers)
	r=response.json()
	r=r['result'][0]
	if len(r['baike_info'])==3:
		return render_template('plant_page.html',name=r['name'],description=r[ 'baike_info']['description'],url=r['baike_info']['baike_url'])
	else:
		return render_template('plant_page.html',name=r['name'],description='暂无百度百科信息',url='/')

@app.route('/plant_page2',methods=['post','get'])
	# 远程植物识别
def plant_page2():
	request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant"
	access_token='24.18c156264044eed43c0f5686eb490329.2592000.1613120716.282335-23488180'
	url=request.form['URL']
	obtain = requests.get(url)
	transform = obtain.content
	img = base64.b64encode(transform)
	params = {"image":img,'baike_num':4}
	request_url = request_url + "?access_token=" + access_token
	headers = {'content-type': 'application/x-www-form-urlencoded'}
	response = requests.post(request_url, data=params, headers=headers)
	r=response.json()
	r=r['result'][0]
	if len(r['baike_info'])==3:
		return render_template('plant_page2.html',name=r['name'],description=r[ 'baike_info']['description'],url=r['baike_info']['baike_url'],img=url)
	# elif r['name']=='非植物':
	# 	return render_template('animals_page2.html',name=r['name'],img=url)
	else:
		return render_template('plant_page2.html',name=r['name'],description="暂无百度百科信息",img=url)

@app.route('/landmark',methods=['get'])
def landmark()->'html':
	return render_template('landmark.html')

@app.route('/animals',methods=['get'])
def animals()->'html':
	return render_template('animals.html')

@app.route('/animals_page',methods=['post'])
	#远程动物识别
def animals_page():
	request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal"
	url=request.form['URL']
	obtain = requests.get(url)
	transform = obtain.content
	img = base64.b64encode(transform)
	params = {"image":img,'top_num':1,'baike_num':4}
	access_token='24.18c156264044eed43c0f5686eb490329.2592000.1613120716.282335-23488180'
	request_url = request_url + "?access_token=" + access_token
	headers = {'content-type': 'application/x-www-form-urlencoded'}
	response = requests.post(request_url, data=params, headers=headers)
	r=response.json()
	r=r['result'][0]
	if len(r['baike_info'])==3:
		return render_template('animals_page.html',name=r['name'],description=r['baike_info']['description'],url=r['baike_info']['baike_url'],img=url)
	else:
		return render_template('animals_page.html',name=r['name'],img=url)

@app.route('/animals_page2',methods=['post'])
	#本地动物识别
def animals_page2():
	request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal"
	path=reques.form['path']
	f=open(path,'rb')
	img = base64.b64encode(f.read())
	params = {"image":img,'top_num':1,'baike_num':4}
	access_token='24.18c156264044eed43c0f5686eb490329.2592000.1613120716.282335-23488180'
	request_url = request_url + "?access_token=" + access_token
	headers = {'content-type': 'application/x-www-form-urlencoded'}
	response = requests.post(request_url, data=params, headers=headers)
	r=response.json()
	r=r['result'][0]
	if len(r['baike_info'])==3:
		return render_template('animals_page2.html',name=r['name'],description=r['baike_info']['description'],url=r['baike_info']['baike_url'],img=r['baike_info']['image_url'])
	else:
		return render_template('animals_page2.html',name=r['name'],img=path)

@app.route('/landmark_page',methods=['post'])
  	#地标
def landmark_page():
	request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/landmark"
	access_token='24.18c156264044eed43c0f5686eb490329.2592000.1613120716.282335-23488180'
	url=request.form['URL']
	obtain = requests.get(url)
	transform = obtain.content
	img = base64.b64encode(transform)
	params = {"image":img}
	request_url = request_url + "?access_token=" + access_token
	headers = {'content-type': 'application/x-www-form-urlencoded'}
	response = requests.post(request_url, data=params, headers=headers)
	r=response.json()
	address=r['result']['landmark']
	key='18ef7dd6aeefc21dade574262c00f213'
	extensions='base'
	city=geocode(key,address,city=None,batch='false',sig=None,output='json',callback=None)['geocodes'][0]['city']
	con=weather(key,city,extensions)
	return render_template('landmark_page.html',img=url,name=address,city=str(city),weather=con['lives'][0]['weather'],T=con['lives'][0]['temperature'],
		wind=con['lives'][0]['winddirection'],power=con['lives'][0]['windpower'])

@app.route('/food',methods=['get'])
def food()->'html':
	return render_template('food.html')

@app.route('/food_page',methods=['post'])
       #美食卡路里
def food_page():
	request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish"
	url=request.form['URL']
	obtain = requests.get(url)
	transform = obtain.content
	img = base64.b64encode(transform)
	params = {"image":img,"top_num":1,"filter_threshold":0.95,"baike_num":3}
	access_token = '24.f9eb41cc60e1ab2dfa880ee9d8e85a73.2592000.1612407569.282335-23488180'
	request_url = request_url + "?access_token=" + access_token
	headers = {'content-type': 'application/x-www-form-urlencoded'}
	response = requests.post(request_url, data=params, headers=headers)
	r=response.json()['result'][0]
	if len(r['baike_info'])==3:
		return render_template('food_page.html',name=r['name'],description=r['baike_info']['description'],calorie=r['calorie'],url=r['baike_info']['baike_url'],img=url,number=r['probability'])
	else:
		return render_template('food_page.html',name=r['name'],description='暂无百度百科信息',calorie=r['calorie'],url='baidu.com',img=url,number=r['probability'])

@app.route('/poem',methods=['get'])
def poem()->'html':
	return render_template('poem.html')

@app.route('/poem_page',methods=['post'])
def poem_page():
	request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general"
	url=request.form['URL']
	obtain=requests.get(url)
	transform=obtain.content
	img = base64.b64encode(transform)
	params = {"image":img}
	access_token = '24.18c156264044eed43c0f5686eb490329.2592000.1613120716.282335-23488180'
	request_url = request_url + "?access_token=" + access_token
	headers = {'content-type': 'application/x-www-form-urlencoded'}
	response = requests.post(request_url, data=params, headers=headers)
	result=response.json()['result'][0]['keyword']
	text=result
	load=poemmake(text,index=0)['poem'][0]['content']
	return render_template('poem_page.html',img=url,T=result,one=load[0:7],two=load[8:15],three=load[16:23],four=load[24:])



@app.route('/frust',methods=['get'])
def frust()->'html':
	return render_template('frust.html')

@app.route('/frust_page',methods=['post'])
	#果蔬识别
def frust_page():
	request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient"
	url=request.form['URL']
	obtain=requests.get(url)
	transform=obtain.content
	img = base64.b64encode(transform)
	params = {"image":img}
	access_token='24.18c156264044eed43c0f5686eb490329.2592000.1613120716.282335-23488180'
	request_url = request_url + "?access_token=" + access_token
	headers = {'content-type': 'application/x-www-form-urlencoded'}
	response = requests.post(request_url, data=params, headers=headers)
	r=response.json()['result']
	# r为result简写 ，p为probability简写
	r0=r[0]
	r1=r[1]
	r2=r[2]
	r3=r[3]
	r4=r[4]
	p1=r[0]['score']
	p2=r[1]['score']
	p3=r[2]['score']
	p4=r[3]['score']
	p5=r[4]['score']
	p1=str(p1)
	p2=str(p2)
	p3=str(p3)
	p4=str(p4)
	p5=str(p5)
	p1=p1[0:5]
	p2=p2[0:5]
	p3=p3[0:5]
	p4=p4[0:5]
	p5=p5[0:5]
	return render_template('frust_page.html',img=url,name1=r[0]['name'],name2=r[1]['name'],name3=r[2]['name'],name4=r[3]['name'],name5=r[4]['name'],
		p1=p1,p2=p2,p3=p3,p4=p4,p5=p5)
	

if __name__ == '__main__':
	app.run(debug= True)


